package com.xxx.blog.web;

import com.xxx.blog.po.Comment;
import com.xxx.blog.po.Reply;
import com.xxx.blog.po.User;
import com.xxx.blog.service.BlogService;
import com.xxx.blog.service.CommentService;
import com.xxx.blog.service.ReplyService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Controller
public class CommentShowController {
    @Resource
    private CommentService commentService;
    @Resource
    private BlogService blogService;
    @Resource
    private ReplyService replyService;


    @Value("${comment.avatar}")
    private String avatar;

    @GetMapping("/comments/{blogId}")
    public String comments(@PathVariable Long blogId, Model model) {
        model.addAttribute("comments", commentService.listCommentByBlogId(blogId));
        return "blog::commentList";
    }

    @PostMapping("/comments")
    public String post(Comment comment, HttpSession session) {
        Long blogId = comment.getBlog().getId();
        comment.setBlog(blogService.getBlog(blogId));
        User user = (User) session.getAttribute("user");
        if (user!=null){
            //管理员评论
            comment.setAvatar(user.getAvatar());
            comment.setAdminComment(true);
            comment.setNickname(user.getNickname());
        }else {
            comment.setAvatar(avatar);
        }
        commentService.saveComment(comment);
        if (comment.getParentComment()!=null){
            Comment c=replyService.findLast();
            Reply reply=new Reply(comment.getParentComment().getId(),c.getId());
            replyService.saveComment(reply);
        }
        return "redirect:/comments/" + blogId;
    }
}
